import VueRouter from 'vue-router';

const routes = [
    {
        path:'/',
        name:'login',
        component:()=>import('../components/Login')
    },
    {
        path:'/Index',
        name:'index',
        component:()=>import('../components/Index'),
        children:[
            {
                path:'/Home',
                name:'home',
                meta:{
                    title:'首页'
                },
                component:()=>import('../components/Home')
            }
        ]
    }
]

// 创建路由实例
const router = new VueRouter({
    mode:'history',
    routes
})

// 登录校验：除登录页外必须携带 JWT
router.beforeEach((to, from, next) => {
    if (to.path === '/') {
        return next();
    }
    const token = sessionStorage.getItem('jwtToken');
    if (!token) {
        return next('/');
    }
    next();
})

// 导出路由
export function resetRouter() {
    router.matcher = new VueRouter({
        mode:'history',
        routes: []
    }).matcher
}

// 覆盖原型方法
const VueRouterPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(to) {
    const promise = VueRouterPush.call(this, to);
    // 检查 promise 是否为 Promise 实例
    if (promise && typeof promise.catch === 'function') {
        // 如果是，直接返回以便可以链式调用 catch
        return promise;
    } else {
        // 如果不是，返回一个解析后的 Promise，以避免调用 catch 时出错
        return Promise.resolve();
    }
};
export  default router;